package com.example.hrandroidapp.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.dobmob.doblist.DobList;
import com.dobmob.doblist.events.OnLoadMoreListener;
import com.dobmob.doblist.exceptions.NoEmptyViewException;
import com.dobmob.doblist.exceptions.NoListViewException;
import com.example.hrandroidapp.OvertimeMailDetailActivity;
import com.example.hrandroidapp.R;
import com.example.hrandroidapp.adapter.OvertimeApprovalAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.domain.OverTimePO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;

public class OvertimeApproveFragment extends Fragment implements OvertimeApprovalAdapter.AcceptCallBack {

	private ListView lstOvertimeAproval;
	private OvertimeApproveFragment fragment=this;
	private List<OverTimePO> lstOvertimes;
	private String url;
	
	private final String OT_APPROVE_STATUS = "2";
	private String lastOvertimeId = "0";
	private boolean myOT = false;
	
	private OvertimeApprovalAdapter otApprovAdpt;
	private DobList dobList;
	
	@Override
	public void onResume() {
		super.onResume();
		loadOvertimes();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_overtime_approve, container, false);
		
		loadViews(rootView);
		loadOvertimes();
	    
	    initDobList(rootView, lstOvertimeAproval);
	    lstOvertimeAproval.setAdapter(otApprovAdpt);
	    otApprovAdpt.setCheckableListView(false);
	    
	    lstOvertimeAproval.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				OverTimePO overtimePO = lstOvertimes.get(position); 
				Intent intent = new Intent(fragment.getActivity().getApplicationContext(), OvertimeMailDetailActivity.class);
				intent.putExtra("ot", overtimePO); 
				intent.putExtra("pending", "0");
				getActivity().startActivity(intent); 
			}
		});
		return rootView;
	}
	
	private void loadViews(View rootView) {
		lstOvertimeAproval = (ListView) rootView.findViewById(R.id.list_ot_approve);
		lstOvertimes = new ArrayList<OverTimePO>();
		otApprovAdpt = new OvertimeApprovalAdapter(fragment.getActivity().getApplicationContext(), lstOvertimes, this);
	}
	
	@Override
	public void setAccptVisible(boolean flag) {}

	private void loadOvertimes() {
		if(isAdded()) {
			url = getResources().getString(R.string.overtime_url);
			String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
			
			HRLog.postLogInfo("leave approve url complete: " + completeUrl, "LeavePendingFragment.loadLeaves"); 
			new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, populateRequestParameterMap(), 
					new HTTPUtils.SimpleRequestResponseTaskInterface() {
	
				@Override
				public void handleResponse(String responseStr, int status) throws Exception {
					HRLog.postLogDebug("JSON string: " + responseStr, "LeavePendingFragment.onCreateView");
					
					JSONArray otArray = new JSONArray(responseStr);
					
					lstOvertimes.clear();
					for (int i = 0; i < otArray.length(); i++) {
	
		                JSONObject jsonobject = otArray.getJSONObject(i);
		                OverTimePO overTimePO = new OverTimePO();
		                
		                overTimePO.setOtID(Integer.parseInt(jsonobject.getString("otId")));
		                overTimePO.setEmployeeName(jsonobject.getString("employeeName"));
		                overTimePO.setReason(jsonobject.getString("reason"));
		                overTimePO.setOtDate(DateUtils.getJavaDate(jsonobject.getString("otDate"))); 
		                overTimePO.setTask(jsonobject.getString("task"));
		                overTimePO.setOtMinutes(Integer.parseInt(jsonobject.getString("otMinutes")));
		                overTimePO.setOtType(Integer.parseInt(jsonobject.getString("otType")));
		                
		                lstOvertimes.add(overTimePO); 
		           }
					
					Collections.sort(lstOvertimes, new Comparator<OverTimePO>() {
	
						@Override
						public int compare(OverTimePO obj1, OverTimePO obj2) {
							return obj2.getCreatedDate().compareTo(obj1.getCreatedDate());
						}
					});
					
					otApprovAdpt = new OvertimeApprovalAdapter(fragment.getActivity().getApplicationContext(), lstOvertimes, fragment);
				    lstOvertimeAproval.setAdapter(otApprovAdpt);
				    
				}
				
			}).execute();
		}	
	}
	
	private void initDobList(View rootView, ListView listView) {

		dobList = new DobList();
		try {

			dobList.register(listView);

			dobList.addDefaultLoadingFooterView();

			// Sets the view to show if the adapter is empty
			// see startCentralLoading() method
			View noItems = rootView.findViewById(R.id.no_ot_items);
			dobList.setEmptyView(noItems);

			// Callback called when reaching last item in ListView
			dobList.setOnLoadMoreListener(new OnLoadMoreListener() {

				@Override
				public void onLoadMore(final int totalItemCount) {

					// Just inserting some dummy data after
					// period of time to simulate waiting
					// data from server
					loadMoreData(10);
				}
			});

		} catch (NoListViewException e) {
			e.printStackTrace();
		}

		try {
			// Show ProgressBar at the center of ListView
			// this can be used while loading data from
			// server at the first time
			//
			// setEmptyView() must be called before
			//
			// NoEmptyViewException will be thrown when
			// there is no EmptyView
			dobList.startCentralLoading();

		} catch (NoEmptyViewException e) {
			e.printStackTrace();
		}
		// Simulate adding data at the first time
		loadMoreData(20);
	}

	protected void loadMoreData(final int itemsCount) {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				addItems(otApprovAdpt.getCount(), otApprovAdpt.getCount() + itemsCount);

				// We must call finishLoading
				// when finishing adding data
				dobList.finishLoading();
			}

		}, 3000);
	}

	protected void addItems(int from, int to) {
//		for(int i=from; i<to; i++) {
//	    	LeavePO leavePO = new LeavePO();
//	    	leavePO.setEmployeeName("Name "+i);
//	    	leavePO.setLeaveDescription("Pending Message " + i);
//	    	Date currentDate = new Date();
//	    	leavePO.setCreatedDate(DateUtils.convert(currentDate, DateUtils.DATE_DDMMYYYY_FORMAT));
//	    	
//	    	leaveApprovAdpt.addLeave(leavePO);
//	    }
	}

	public Map<String, String> populateRequestParameterMap() {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("overtimeStatus", OT_APPROVE_STATUS);
		paramMap.put("overtimeId", lastOvertimeId);
		paramMap.put("loginId", UserPreference.getLoginId(getActivity()));
		paramMap.put("size", String.valueOf(Constant.OVERTIME_SIZE));
		paramMap.put("myOvertime", String.valueOf(myOT));
		return paramMap;
	}
}
